package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author da
 * @Date 2021/8/15 下午 1:59
 */
@RestController
@RequestMapping("/book")
public class BookController
{
    @Resource
    BookMapper BookMapper;

    //    插入书籍
    @PostMapping
    public Result<?> save(@RequestBody Book book)
    {
        BookMapper.insert(book);
        return Result.success();
    }

    //    更新书籍
    @PutMapping
    public Result<?> update(@RequestBody Book book)
    {
        BookMapper.updateById(book);
        return Result.success();
    }

    //    删除书籍
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id)
    {
        BookMapper.deleteById(id);
        return Result.success();
    }

    //    通过id获取书籍
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id)
    {
        return Result.success(BookMapper.selectById(id));
    }

    //    分页查询
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search)
    {
        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
//        search不为空才模糊查询
        if (StrUtil.isNotBlank(search))
        {
            wrapper.like(Book::getName, search);
        }
        Page<Book> bookPage = BookMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(bookPage);
    }
}
